package com.ubing.boot.notesforjava.test.NIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @ClassName : sokect_NIO
 * @Description : sokect_NIO
 * @Author : Xxxxx
 * @Date: 2023-03-25 17:06
 */
public class sokect_NIO {
    // 保存客户端链接
    static List<SocketChannel> channelList=new ArrayList<SocketChannel>();

    public static void main(String[] args) throws IOException {
        //创建NIO
        ServerSocketChannel serverSocket=ServerSocketChannel.open();
        serverSocket.socket().bind(new InetSocketAddress(9090));
        // 设置socket为非阻塞
        serverSocket.configureBlocking(false);
        System.out.println("服务启动成功");
        while(true){
            // 非阻塞accept不会阻塞
            SocketChannel socketChannel = serverSocket.accept();// 因为serverSocket配置为非阻塞，因此不会阻塞，向下执行
            //NIO 的非阻塞是由操作系统内部实现，底层调用了linux内核的accept函数
            if(socketChannel!=null){
                System.out.println("连接成功");
                //设置socketChannel为非阻塞
                socketChannel.configureBlocking(false);
                // 保存链接到List中
                channelList.add(socketChannel);
            }
            Iterator<SocketChannel> iterator = channelList.iterator();
            while (iterator.hasNext()){
                SocketChannel sc = iterator.next();
                ByteBuffer byteBuffer = ByteBuffer.allocate(6);
                // socketChannel为非阻塞模式，不会阻塞
                int len = sc.read(byteBuffer);
                // 如果有数据，把数据打印
                if(len>0){
                    System.out.println("接受的数据："+new String(byteBuffer.array()));
                } else if(len==-1){
                    iterator.remove();
                    System.out.println("客户端断开链接");

                }
            }

        }
    }

}
